package com.tlkg.qa.utils.springcofig;

import java.util.Map;
import java.util.TreeSet;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.util.JedisClusterCRC16;

public class RedisUtil {

	public static JedisCluster jedisCluster;

	static {
		jedisCluster = new ClassPathXmlApplicationContext("spring-redis.xml").getBean("jedisCluster",
				JedisCluster.class);
	}

	/**
	 * 设置缓存
	 *
	 * @return
	 */
	public static String set(String key, String value) {
		return jedisCluster.set(key, value);
	}

	/**
	 * 获取缓存
	 *
	 * @return
	 */
	public static String get(String name) {
		return jedisCluster.get(name);
	}

	public static TreeSet<String> keys(String pattern) {
		TreeSet<String> keys = new TreeSet<>();
		Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
		for (String k : clusterNodes.keySet()) {
			JedisPool jp = clusterNodes.get(k);
			Jedis connection = jp.getResource();
			try {
				keys.addAll(connection.keys(pattern));
			} catch (Exception e) {
			} finally {
				connection.close();// 用完一定要close这个链接！！！
			}
		}
		return keys;
	}

	public static int getSlot(String key) {
		// 这东西 可以直接看到key 的分片数，就能知道放哪个 节点
		return JedisClusterCRC16.getSlot(key);
	}

}
